package com.guge.sports.toolPackage.base;

import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.guge.sports.toolPackage.anno.FileField;
import com.guge.sports.toolPackage.utils.ApplicationContextUtils;
import com.guge.sports.toolPackage.utils.MyPager;
import com.guge.sports.utils.R;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;


public class BaseController<T extends Model> implements InitializingBean {


    protected BaseService<T> baseService;

    /**
     * 通过判断mapper泛型得到mapper
     */
    protected void initService() {
        BaseService baseService = ApplicationContextUtils.getServiceByGenericType(getClass());
        //System.out.println("baseService="+baseService);
        if (baseService != null) {
            this.baseService = baseService;
        }
    }

   /* @ApiOperation(value = "查询所有")
    @GetMapping("/selectAll")
    @ResponseBody
    public Object selectAll() {
        return baseService.selectAll();
    }*/


    /**
     * @param entity
     * @return
     */
    @ApiOperation(value = "根据条件查询，条件封装在实体类")
    @PostMapping("/selectList")
    @ResponseBody
    public R selectList(@RequestBody(required = false) T entity) {
        return R.ok().data("list",baseService.selectList(entity));

    }

    @ApiOperation(value = "条件查询一个结果，条件封装在实体类")
    @PostMapping("/selectOne")
    @ResponseBody
    public R selectOne(@RequestBody T entity) {

        return R.ok().data("one",baseService.selectOne(entity));
    }

    /*@ApiOperation(value = "通过id进行查询")
    @PostMapping("/selectById")
    @ResponseBody
    public Object selectById(T entity) {
        return baseService.selectById(entity);
    }

    @ApiOperation(value = "通过id进行批量查询")
    @PostMapping("/selectBatchIds")
    @ResponseBody
    public Object selectBatchIds(@RequestBody List<Integer> ids) {
        return baseService.selectBatchIds(ids);
    }
*/
    /*@ApiOperation(value = "查询总数")
    @GetMapping("/selectAllCount")
    @ResponseBody
    public Object selectAllCount() {
        return baseService.selectAllCount();
    }

    @ApiOperation(value = "根据条件查询总数")
    @PostMapping("/selectCount")
    @ResponseBody
    public Object selectCount(T entity) {
        return baseService.selectCount(entity);
    }
*/


    /*@ApiOperation(value = "通过id进行删除")
    @DeleteMapping("/deleteById")
    @ResponseBody
    public Object deleteById(@RequestBody T entity) {
        return baseService.deleteById(entity);
    }
*/



    @ApiOperation(value = "通过id进行批量删除")
    @DeleteMapping("/deleteBatchIds")
    @ResponseBody
    public R deleteBatchIds(@RequestBody List<Integer> ids) {

        return R.result(baseService.deleteBatchIds(ids));
    }

    @ApiOperation(value = "条件删除，条件封装在实体类")
    @DeleteMapping("/delete")
    @ResponseBody
    public R delete(@RequestBody T entity) {
        return R.result(baseService.delete(entity));
    }

    @ApiOperation(value = "通过id进行更新")
    @PutMapping("/updateById")
    @ResponseBody
    public R updateById(@RequestBody T entity) {
        return R.result(baseService.updateById(entity));

    }

    @ApiOperation(value = "插入")
    @PostMapping("/insert")
    @ResponseBody
    public R insert(@RequestBody T entity) {

        return R.result(baseService.insert(entity));
    }


    //分页查询
    @ApiOperation(value = "分页查询")
    @PostMapping("/selectPage")
    @ResponseBody
    public R selectPage(MyPager<T> myPager,@RequestBody T entity) {
        //myPager.setEntity(entity);
        System.out.println("myPager="+myPager);
        //System.out.println("entity="+entity);
        return R.ok().data("page",baseService.selectPage(myPager,entity));
    }

/*    MyPager<T> selectPageCondition(MyPager<T> myPager, T entity) {
        return null;
    }*/



   /* @Value("${pro.uploadPath}")
    private String uploadPath;

    public final static String UPLOAD_PATH_PREFIX = "src/main/resources/static/backend/upload";

*/

    /**
     * 获取文件路径
     * @param request 请求体
     * @param //fileName 文件名称
     * @return 文件路径
    public String getUploadPath(HttpServletRequest request, String fileName) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + uploadPath + "/" + fileName;
    }*/



    //文件上传
    @ApiOperation(value = "文件上传")
    @PostMapping("/upload")
    @ResponseBody
    public R upload( T entity, MultipartFile uploadFile, HttpServletRequest request) throws IOException {
        System.out.println("---------文件上传----------");
        String filename = uploadFile.getOriginalFilename();
        System.out.println("filename="+filename);

      /*  String uploadPath = getUploadPath(request, filename);
        System.out.println("uploadPath=="+uploadPath);*/

        String subString = filename.substring(filename.lastIndexOf("."));
        filename = UUID.randomUUID().toString().replaceAll("-", "") + subString;
        String realName =  ResourceUtils.getURL("classpath:").getPath()+"static/backend/upload/";

        File uploadfile=new File(realName);
        if(!uploadfile.exists()){
            uploadfile.mkdirs();
        }

        System.out.println("realName===="+realName);
        //upUser.setImageName("upload/"+filename);
        uploadFile.transferTo(new File(realName + filename));
        setFileField(entity, "backend/upload/" + filename);
        return R.result(baseService.insert(entity));
    }


    private void setFileField(T entity, String url) {
        Field[] declaredFields = entity.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            if (declaredField.isAnnotationPresent(FileField.class)) {
                try {
                    declaredField.set(entity, url);
                    break;
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    throw new RuntimeException("反射失败");
                }
            }
        }

    }

    //重写接口方法
    @Override
    public void afterPropertiesSet() throws Exception {
        //System.out.println("属性初始化-----service-------");
        initService();
    }

    /**
     * 返回json格式信息
     *
     * @param
     * @throws
     */
   /* private HashMap<String, String> sendJsonResult(boolean b) {
        HashMap<String, String> hashMap = new HashMap<>();
        if (b) {
            hashMap.put("state", "success");
        } else {
            hashMap.put("state", "error");
        }
        return hashMap;
    }*/


   /* @GetMapping("/hello")
    public String hello(HttpServletRequest request) {
        System.out.println("uploadPath --> " + uploadPath);
        System.out.println("上下文2 --> " + request.getServletContext().getRealPath("/file"));

        File file = new File(UPLOAD_PATH_PREFIX);
        System.out.println("UPLOAD_PATH_PREFIX 路径: " + file.getAbsoluteFile());

        try {
            String path = ResourceUtils.getURL("classpath:").getPath();

            //-------------
            System.out.println("ResourceUtils.getURL.getPath --> " + path);

            System.out.println("当前项目的绝对路径 --> " + new File("").getAbsolutePath());
            System.out.println("upload 绝对路径 --> " + new File("upload").getAbsolutePath());
            System.out.println("/upload 绝对路径 --> " + new File("/upload").getAbsolutePath());
            System.out.println("./upload 绝对路径 --> " + new File("./upload").getAbsolutePath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());
        return format;
    }*/


    /*@Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //System.out.println("spring初始化完成。。。");
        initService();
    }*/


}
